/*
 * @lc app=leetcode.cn id=1160 lang=typescript
 *
 * [1160] 拼写单词
 */

// @lc code=start
function countCharacters(words: string[], chars: string): number {
    let cache: number[] = new Array(26).fill(0);

    for (const iterator of chars) {
        cache[iterator.charCodeAt(0) - 97] += 1;
    }
    const charInWord = (word: string) => {
        let counter = [...cache];
        for (const iterator of word) {
            let count = counter[iterator.charCodeAt(0) - 97];
            if (count <= 0) {
                return false;
            } else {
                counter[iterator.charCodeAt(0) - 97]--;
            }
        }
        return true;
    };
    return words
        .filter((i) => {
            return charInWord(i);
        })
        .reduce((a, b) => a + b.length, 0);
}
// @lc code=end
